<template>
  <div class="login-wrapper">
    <div class="model">
      <el-form ref="userFromRef" :model="user" :rules="rules">
        <div class="title">通用后台管理</div>
        <el-form-item prop="userName">
          <el-input
            ref="name"
            v-model="user.userName"
            prefix-icon="User"
            @change="userName"
          />
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input
            ref="pwd"
            v-model="user.userPwd"
            type="password"
            show-password
            prefix-icon="Lock"
            @keyup.enter.native="pwdEnter(userFromRef)"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="btn" @click="login(userFromRef)" type="primary"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import api from '../api'
import message from '../utils/message.js'
import { ref, reactive, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router';
const router = useRouter()
const store = useStore()
let user = reactive({ userName: "", userPwd: "" })
let rules = reactive({
  userName: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    { pattern: /^[A-Za-z]+$/, message: "用户名必须是英文" }
  ],
  userPwd: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    { pattern: /^\d{6}$/, message: "密码六位纯数字" }
  ]
})
let userFromRef = ref(null)
const name = ref(null)
const pwd = ref(null)
const userName = (val) => {
  pwd.value.focus()
}
const pwdEnter = (val) => {
  login(val)
}

// proxy 劫持对象,可以找到$api proxy.$api.login()
const { proxy } = getCurrentInstance();
// 登录
const login = (val) => {
  val.validate((vaild) => {
    // console.log(vaild);
    // 根据刚刚设置的rules去匹配，都满足返回true
    // 只要一个不满足返回false
    if (vaild) {
      // 发送请求
      api.login(user).then(res => {
        // 获取token 保存
        // token要保存在vuex
        store.commit('saveUserInfo', res)
        // 跳转到首页
        router.push('/')
        message.message('登录成功!', 'success')
      }).catch(str => {
        message.message('账号或密码错误!', 'error')
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background: url("../assets/banner.svg") no-repeat center;
  background-size: cover;
  position: absolute;
  left: 0;
  top: 0;
  .model {
    width: 500px;
    padding: 50px;
    background-color: #fff;
    box-shadow: 0px 0px 10px 3px #ddd;
    border-radius: 5px;
    .title {
      text-align: center;
      font-size: 40px;
      margin-bottom: 30px;
      line-height: 1.5;
    }
    .btn {
      width: 100%;
    }
  }
}
</style>